#include "ceudpsocket.h"

#include <QTimer>

CeUdpSocket::CeUdpSocket(const quint16 port, QObject *parent):
    QUdpSocket(parent), m_port(port)
{
//    connect(timer, SIGNAL(timeout()), this, SLOT(timeOut()));
//    timer->start(1 * 1000);

    init();
}

CeUdpSocket::~CeUdpSocket()
{
//    qDebug() << "CeUdpSocket ============>";
}

void CeUdpSocket::init()
{
//    qDebug() << "udp bind=============start========> m_port" << m_port;
    this->bind(7756, QUdpSocket::ShareAddress);
//    this->connectToHost(QHostAddress::LocalHost, 7755);
    connect(this,SIGNAL(readyRead()),this,SLOT(recv_slot()));
}


void CeUdpSocket::sendRouteAck(const UBYTE result)
{
    PIDS_Ack pids_ack;

    pids_ack.BaseFiles.PriCmd = PRICMD_CEANDPIDS;
    pids_ack.BaseFiles.SubCmd = SUBCMD_SENDROUTEACK;
    pids_ack.result = result;

    int len = sizeof(pids_ack);
    int plen = 6 + len;
    UBYTE *pCode = new UBYTE[plen];
    pCode[0]= (quint8)0x3C;
    pCode[1]= (quint8)0x21;
    pCode[2]= (quint8)(len>>8);
    pCode[3]= (quint8)(len%256);
    memcpy(pCode+4, &pids_ack, len);

    pCode[len+4] = (quint8)0x21;
    pCode[len+5] = (quint8)0x3E;
    this->writeDatagram(pCode, plen, QHostAddress::LocalHost, 7755);
//    qDebug() << result << len << "==== sendRouteAck ====" << this->writeDatagram(pCode, plen, QHostAddress("192.168.1.57"), 7755);

}

void CeUdpSocket::ctlPIDSAck(const UBYTE type, const UBYTE result)
{
    PIDS_Ack pids_ack;

    pids_ack.BaseFiles.PriCmd = PRICMD_CONTROLPIDS;
    pids_ack.BaseFiles.SubCmd = type;
    pids_ack.result = result;

    int len = sizeof(pids_ack);
    int plen = 6 + len;
    UBYTE *pCode = new UBYTE[plen];
    pCode[0]= (quint8)0x3C;
    pCode[1]= (quint8)0x21;
    pCode[2]= (quint8)(len>>8);
    pCode[3]= (quint8)(len%256);
    memcpy(pCode+4, &pids_ack, len);

    pCode[len+4] = (quint8)0x21;
    pCode[len+5] = (quint8)0x3E;
    this->writeDatagram(pCode, plen, QHostAddress::LocalHost, 7755);
//    qDebug() << len << "==== ctlPIDSAck ====" << this->writeDatagram(pCode, plen, QHostAddress("192.168.1.57"), 7755);

}


void CeUdpSocket::recv_slot()
{
//    qDebug()<<"in recv_slot()================================" << this->bytesAvailable();
    while(this->hasPendingDatagrams())
    {

        UBYTE result;
        if (this->pendingDatagramSize() < 8)
            return;

        QByteArray receBytes;
        receBytes.resize(this->pendingDatagramSize());
        this->readDatagram(receBytes.data(), receBytes.size());

        qint16 header, len, eof;
        QDataStream receStream(&receBytes, QIODevice::ReadOnly);
        receStream.setVersion(QDataStream::Qt_4_6);

        receStream >> header >> len;

        receStream.skipRawData(len);
        receStream >> eof;

        if (header == quint16(0x3c21))
        {
//            qDebug() << "header success---------->>";
        } else {
//            qDebug() << "header fail---------->>";
            return;
        }

        PIDS_RouteMsg       PIDS_routeMsg;
        PIDS_ControlPIDS    PIDS_controlPIDS;

        if (len > 10)
        {
            memcpy(&PIDS_routeMsg, receBytes.data()+4, sizeof(PIDS_routeMsg));

            if (eof != quint16(0x213E))
            {
                result = 0;
            } else {
                result = 1;
                emit receRouteMsg(PIDS_routeMsg);
            }
            this->sendRouteAck(result);
        } else {

            memcpy(&PIDS_controlPIDS, receBytes.data()+4, sizeof(PIDS_controlPIDS));

            UBYTE result;
            if (eof != quint16(0x213E))
            {
                result = 0;
            } else {
                result = 1;
                emit receCtlCmd(PIDS_controlPIDS);
            }

            this->ctlPIDSAck(PIDS_controlPIDS.BaseFiles.SubCmd, result);
        }

    }

}

void CeUdpSocket::timeOut()
{
//    qDebug() <<  "CeUdpSocket ==================== >" << this->bytesAvailable();
}
